home *** CD-ROM | disk | FTP | other *** search
/ Reverse Code Engineering RCE CD +sandman 2000 / ReverseCodeEngineeringRceCdsandman2000.iso / RCE / Ebooks / Thinking in C++ V2 / C07 / Stash3.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2000-05-25  |  1.7 KB  |  70 lines

  1. //: C07:Stash3.cpp {O}
  2. // From Thinking in C++, 2nd Edition
  3. // Available at http://www.BruceEckel.com
  4. // (c) Bruce Eckel 1999
  5. // Copyright notice in Copyright.txt
  6. // Function overloading
  7. #include "Stash3.h"
  8. #include <iostream>
  9. #include <cassert>
  10. using namespace std;
  11. const int increment = 100;
  12.  
  13. Stash::Stash(int sz) {
  14.   size = sz;
  15.   quantity = 0;
  16.   next = 0;
  17.   storage = 0;
  18. }
  19.  
  20. Stash::Stash(int sz, int initQuant) {
  21.   size = sz;
  22.   quantity = 0;
  23.   next = 0;
  24.   storage = 0;
  25.   inflate(initQuant);
  26. }
  27.  
  28. Stash::~Stash() {
  29.   if(storage != 0) {
  30.     cout << "freeing storage" << endl;
  31.     delete []storage;
  32.   }
  33. }
  34.  
  35. int Stash::add(void* element) {
  36.   if(next >= quantity) // Enough space left?
  37.     inflate(increment);
  38.   // Copy element into storage,
  39.   // starting at next empty space:
  40.   int startBytes = next * size;
  41.   unsigned char* e = (unsigned char*)element;
  42.   for(int i = 0; i < size; i++)
  43.     storage[startBytes + i] = e[i];
  44.   next++;
  45.   return(next - 1); // Index number
  46. }
  47.  
  48. void* Stash::fetch(int index) {
  49.   assert(0 <= index && index < next);
  50.   // Produce pointer to desired element:
  51.   return &(storage[index * size]);
  52. }
  53.  
  54. int Stash::count() {
  55.   return next; // Number of elements in CStash
  56. }
  57.  
  58. void Stash::inflate(int increase) {
  59.   assert(increase > 0);
  60.   int newQuantity = quantity + increase;
  61.   int newBytes = newQuantity * size;
  62.   int oldBytes = quantity * size;
  63.   unsigned char* b = new unsigned char[newBytes];
  64.   for(int i = 0; i < oldBytes; i++)
  65.     b[i] = storage[i]; // Copy old to new
  66.   delete [](storage); // Release old storage
  67.   storage = b; // Point to new memory
  68.   quantity = newQuantity; // Adjust the size
  69. } ///:~
  70.